﻿using Castle.Facilities.FactorySupport;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using CommonServiceLocator.WindsorAdapter;
using DMS.DAOs;
using DMS.DAOs.NH;
using DMS.DAOs.NH.Castle;
using DMS.Mappers;
using DMS.Mappers.AutoMapper;
using DMS.Mappers.Reload;
using DMS.Models;
using DMS.Models.Impl;
using DMS.Services;
using DMS.Services.Impl;
using Microsoft.Practices.ServiceLocation;
using NHibernate;

namespace DMS.ServiceLocation
{
    public class ServiceLocatorFactory
    {
        public static IServiceLocator GetServiceLocator()
        {
            return new WindsorServiceLocator(GetContainer());
        }

        private static IWindsorContainer GetContainer()
        {
			//Container
            IWindsorContainer container = new WindsorContainer();

			//Facilities
            container.AddFacility("factory.support", new FactorySupportFacility());
            
			//Session Managment
            container.Register(Component.For<SessionFactoryProvider>()
                              .ImplementedBy<SessionFactoryProvider>()
                              .LifeStyle.Singleton)
                .Register(Component.For<ISessionFactory>()
                              .UsingFactoryMethod(
                              kernel => kernel.Resolve<SessionFactoryProvider>().BuildSessionFactory())
                              .LifeStyle.Singleton)
                .Register(Component.For<SessionInterceptor>()
                              .ImplementedBy<SessionInterceptor>());

            //All DAOs
            container.Register(
                AllTypes.Of<IDAO>()
                    .From(typeof(InvoiceDAO).Assembly.GetTypes())
                    .WithService.FromInterface()
                    .Configure(cr => cr.LifeStyle.Singleton));

			//All Models
			container.Register(
				AllTypes.Of<IModel>()
					.From(typeof(MarketingModel).Assembly.GetTypes())
					.WithService.FromInterface()
					.Configure(cr => cr.LifeStyle.Transient));

            //Each Mappers
            container.Register(Component.For<IMapperBEtoDTO>().ImplementedBy<MapperBEtoDTO>().LifeStyle.Singleton)
                .Register(Component.For<IMapperDTOtoBE>().ImplementedBy<MapperDTOtoBE>().LifeStyle.Singleton);

            //All Services
            container.Register(
                AllTypes.Of<IService>()
                    .From(typeof(InvoiceService).Assembly.GetTypes())
                    .WithService.FromInterface()
                    .Configure(cr => cr.Interceptors<SessionInterceptor>()));

            return container;
        }
    }
}
